#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
水文绘图Web API接口
基于Flask框架，提供HTTP API调用绘图功能
"""

import matplotlib
# 确保使用非交互式后端，防止多线程问题
matplotlib.use('Agg')

from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
import json
from typing import Dict, Any
from draw_hydrology_api import plot_hydrology_map, PlottingParameters, create_hydrology_map
import time

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置
app.config['JSON_AS_ASCII'] = False  # 支持中文JSON响应
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 限制上传文件大小为16MB

@app.route('/', methods=['GET'])
def home():
    """API首页"""
    return jsonify({
        "message": "水文绘图API接口",
        "version": "1.0.0",
        "endpoints": {
            "GET /": "API首页",
            "GET /api/files": "获取可用的NC文件列表",
            "POST /api/plot": "生成地图图片",
            "GET /api/plot/<filename>": "获取生成的图片文件",
            "GET /api/health": "健康检查"
        }
    })

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "message": "API服务正常运行"
    })

@app.route('/api/files', methods=['GET'])
def get_available_files():
    """获取data文件夹中可用的NC文件列表"""
    try:
        data_dir = "data"
        if not os.path.exists(data_dir):
            return jsonify({
                "status": "error",
                "message": "data文件夹不存在"
            }), 404
        
        # 获取所有.nc文件
        nc_files = []
        for file in os.listdir(data_dir):
            if file.endswith('.nc'):
                file_path = os.path.join(data_dir, file)
                file_size = os.path.getsize(file_path)
                nc_files.append({
                    "filename": file,
                    "size": file_size,
                    "size_mb": round(file_size / (1024 * 1024), 2)
                })
        
        return jsonify({
            "status": "success",
            "files": nc_files,
            "total_files": len(nc_files)
        })
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route('/api/plot', methods=['POST'])
def create_plot():
    """生成地图图片的主接口"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify({
                "status": "error",
                "message": "请求数据不能为空"
            }), 400
        
        # 验证必需参数
        required_fields = ['nc_filename', 'variable']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    "status": "error",
                    "message": f"缺少必需参数: {field}"
                }), 400
        
        # 如果要生成GIF，验证GIF相关参数
        if data.get('create_gif', False):
            if not data.get('gif_file_pattern'):
                return jsonify({
                    "status": "error",
                    "message": "生成GIF需要提供gif_file_pattern参数"
                }), 400
        
        # 构建绘图参数
        plot_params = {
            'nc_filename': data['nc_filename'],
            'variable': data['variable'],
            'level': data.get('level', 0),
            'uv_nc_filename': data.get('uv_nc_filename'),
            'u_var': data.get('u_var'),
            'v_var': data.get('v_var'),
            'output_filename': data.get('output_filename'),
            'figsize': tuple(data.get('figsize', [12, 10])),
            'dpi': data.get('dpi', 300),
            'title': data.get('title'),
            'add_north_arrow': data.get('add_north_arrow', True),
            'add_scale_bar': data.get('add_scale_bar', True),
            'scale_bar_length': data.get('scale_bar_length', 200),
            'skip_arrows': data.get('skip_arrows', 1),
            'create_gif': data.get('create_gif', False),
            'gif_file_pattern': data.get('gif_file_pattern'),
            'gif_duration': data.get('gif_duration', 0.8),
            'gif_loop': data.get('gif_loop', 0),
            'gif_vmin': data.get('gif_vmin'),
            'gif_vmax': data.get('gif_vmax'),
            'gif_levels': data.get('gif_levels', 20),
            'gif_integer_levels': data.get('gif_integer_levels', True)
        }
        
        # 调用绘图函数
        try:
            result = plot_hydrology_map(**plot_params)
            
            # 处理返回结果
            if result['status'] == 'success':
                # 返回成功响应，包含图片URL
                response_data = {
                    "status": "success",
                    "message": "地图生成成功",
                    "data": {
                        "output_path": result['output_path'],
                        "relative_path": result['relative_path'],
                        "download_url": f"/api/plot/{os.path.basename(result['relative_path'])}",
                        "metadata": result['metadata']
                    }
                }
                return jsonify(response_data), 200
            else:
                return jsonify({
                    "status": "error",
                    "message": result['message']
                }), 500
        except Exception as plot_error:
            # 如果绘图过程发生异常，确保清理资源
            import matplotlib.pyplot as plt
            plt.close('all')
            return jsonify({
                "status": "error",
                "message": f"绘图过程发生错误: {str(plot_error)}"
            }), 500
            
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": f"服务器内部错误: {str(e)}"
        }), 500

@app.route('/api/plot/<filename>', methods=['GET'])
def get_plot_image(filename):
    """获取生成的图片文件"""
    try:
        # 构建文件路径
        file_path = os.path.join("img", filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            return jsonify({
                "status": "error",
                "message": f"文件不存在: {filename}"
            }), 404
        
        # 返回文件
        return send_file(file_path, as_attachment=True)
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route('/api/plot/preview/<filename>', methods=['GET'])
def preview_plot_image(filename):
    """预览生成的图片文件（不下载）"""
    try:
        # 构建文件路径
        file_path = os.path.join("img", filename)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            return jsonify({
                "status": "error",
                "message": f"文件不存在: {filename}"
            }), 404
        
        # 返回文件用于预览
        return send_file(file_path)
        
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({
        "status": "error",
        "message": "API端点不存在"
    }), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({
        "status": "error",
        "message": "服务器内部错误"
    }), 500

if __name__ == '__main__':
    # 确保必要的目录存在
    os.makedirs("img", exist_ok=True)
    os.makedirs("data", exist_ok=True)
    
    # 清理任何现有的matplotlib图形
    import matplotlib.pyplot as plt
    plt.close('all')
    
    print("启动水文绘图API服务器...")
    print("matplotlib后端:", matplotlib.get_backend())
    print("服务器地址: http://0.0.0.0:5000")
    print("API文档: http://0.0.0.0:5000/")
    
    # 启动开发服务器
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True,
        threaded=True,
        # 禁用reloader以避免在多线程环境中的问题
        use_reloader=False
    )